<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  
    
      
    

    
  

  

  
    
    
    <link href="https://fonts.loli.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Lobster:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.ico?v=5.1.4" color="#222">


  <link rel="manifest" href="/images/manifest.json">




  <meta name="keywords" content="kaggle,NLP,sentiment analysis," />










<meta name="description" content="说起sentiment analysis，就不得不说起NLP选手必做题：Bag of Words Meets Bags of Popcorn ，以下简称“影评分析题”。必须负责任的说，这是一道很简单的题，就是对一段影评进行情感倾向预测（positive/negative）。数据为英文文本，数据集自己下载：🔗data">
<meta name="keywords" content="kaggle,NLP,sentiment analysis">
<meta property="og:type" content="article">
<meta property="og:title" content="Kaggle - Bag of Words Meets Bags of Popcorn">
<meta property="og:url" content="http://codewithzhangyi.com/2019/03/12/kaggle-movie-reviews/index.html">
<meta property="og:site_name" content="Zhang Yi">
<meta property="og:description" content="说起sentiment analysis，就不得不说起NLP选手必做题：Bag of Words Meets Bags of Popcorn ，以下简称“影评分析题”。必须负责任的说，这是一道很简单的题，就是对一段影评进行情感倾向预测（positive/negative）。数据为英文文本，数据集自己下载：🔗data">
<meta property="og:locale" content="en">
<meta property="og:updated_time" content="2019-03-12T15:34:34.754Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Kaggle - Bag of Words Meets Bags of Popcorn">
<meta name="twitter:description" content="说起sentiment analysis，就不得不说起NLP选手必做题：Bag of Words Meets Bags of Popcorn ，以下简称“影评分析题”。必须负责任的说，这是一道很简单的题，就是对一段影评进行情感倾向预测（positive/negative）。数据为英文文本，数据集自己下载：🔗data">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://codewithzhangyi.com/2019/03/12/kaggle-movie-reviews/"/>






<script data-ad-client="ca-pub-2691877571661707" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
  <title>Kaggle - Bag of Words Meets Bags of Popcorn | Zhang Yi</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zhang Yi</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle" style="color:#fff">
    <button>MENU</button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-projects">
          <a href="/projects/" rel="section">
            
            Projects
          </a>
        </li>
      
        
        <li class="menu-item menu-item-blog">
          <a href="/blog/" rel="section">
            
            Blog
          </a>
        </li>
      
        
        <li class="menu-item menu-item-activity">
          <a href="/activity/" rel="section">
            
            Activity
          </a>
        </li>
      
        
        <li class="menu-item menu-item-list-100">
          <a href="/list-100/" rel="section">
            
            List 100
          </a>
        </li>
      
        
        <li class="menu-item menu-item-friends">
          <a href="/friends/" rel="section">
            
            Friends
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://codewithzhangyi.com/2019/03/12/kaggle-movie-reviews/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ZhangYi">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zhang Yi">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Kaggle - Bag of Words Meets Bags of Popcorn</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-03-12T21:56:19+08:00">
                2019-03-12
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/03/12/kaggle-movie-reviews/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2019/03/12/kaggle-movie-reviews/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>visitors
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>说起sentiment analysis，就不得不说起NLP选手必做题：<a href="https://www.kaggle.com/c/word2vec-nlp-tutorial" target="_blank" rel="noopener">Bag of Words Meets Bags of Popcorn</a> ，以下简称“影评分析题”。必须负责任的说，这是一道很简单的题，就是对一段影评进行情感倾向预测（positive/negative）。数据为英文文本，数据集自己下载：<a href="https://www.kaggle.com/c/word2vec-nlp-tutorial/data" target="_blank" rel="noopener">🔗data</a> </p>
<a id="more"></a>
<h3 id="文本清洗技巧"><a href="#文本清洗技巧" class="headerlink" title="文本清洗技巧"></a>文本清洗技巧</h3><h4 id="1-re：正则表达式-Regular-Expression"><a href="#1-re：正则表达式-Regular-Expression" class="headerlink" title="1. re：正则表达式 Regular Expression"></a><strong>1. re：正则表达式 Regular Expression</strong></h4><h5 id="中文处理："><a href="#中文处理：" class="headerlink" title="中文处理："></a>中文处理：</h5><p>除了中文，其他字符全部去掉。这样处理后的output只剩下中文和连接断句的逗号。这个是把非中文的字符比如数字、英文、标点符号、html文本等全部洗掉了，比较狠。这个技能在中文数据集上会比较有用。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">only_chinese</span><span class="params">(comment)</span>:</span></span><br><span class="line">	line = comment.strip()                <span class="comment"># 去除首尾空格</span></span><br><span class="line">	p2 = re.compile(<span class="string">u'[^\u4e00-\u9fa5]'</span>)  <span class="comment"># 中文的编码范围是：\u4e00到\u9fa5</span></span><br><span class="line">	zh = <span class="string">" "</span>.join(p2.split(line)).strip()</span><br><span class="line">	outStr = <span class="string">","</span>.join(zh.split())		  <span class="comment"># 所有的断句全部用逗号连接</span></span><br><span class="line">	<span class="keyword">return</span> outStr</span><br><span class="line"></span><br><span class="line">comment = <span class="string">" 武林外传的情节设计基本没什么bug！╭(●｀∀´●)╯!!\</span></span><br><span class="line"><span class="string">			看了10年都看不腻~送你个网pan链接：\</span></span><br><span class="line"><span class="string">			http://fakewebsite.com"</span></span><br><span class="line"></span><br><span class="line">test = only_chinese(comment)</span><br><span class="line">print(test)</span><br><span class="line"></span><br><span class="line"><span class="comment"># output</span></span><br><span class="line"><span class="comment"># 武林外传的情节设计基本没什么,看了,年都看不腻,送你个网,链接</span></span><br></pre></td></tr></table></figure>
<h5 id="英文处理："><a href="#英文处理：" class="headerlink" title="英文处理："></a>英文处理：</h5><p>除了英文字母，其他字符全部替换为空格。正则表达式就是专治各种不服。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line">comment = <span class="string">'最喜欢的话是Coding is the new SEXY!'</span></span><br><span class="line">review_text = re.sub(<span class="string">"[^a-zA-Z]"</span>,<span class="string">" "</span>,comment)</span><br><span class="line">print(review_text)</span><br><span class="line"></span><br><span class="line"><span class="comment">#       Coding is the new SEXY</span></span><br></pre></td></tr></table></figure>
<h4 id="2-BeautifulSoup：清洗HTML、垃圾符号"><a href="#2-BeautifulSoup：清洗HTML、垃圾符号" class="headerlink" title="2. BeautifulSoup：清洗HTML、垃圾符号"></a>2. BeautifulSoup：清洗HTML、垃圾符号</h4><p>很多网上爬下来的评价内容会带有HTML类型的文本，都是无效信息需要删除，首先”pip install beautifulsoup4“</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> bs4 <span class="keyword">import</span> BeautifulSoup</span><br><span class="line"></span><br><span class="line">review = <span class="string">'&lt;br /&gt;&lt;br /&gt;\"Elvira, Mistress of the Dark\"'</span></span><br><span class="line">review_text = BeautifulSoup(review).get_text()</span><br><span class="line">print(review_text)</span><br><span class="line"></span><br><span class="line"><span class="comment"># "Elvira, Mistress of the Dark"</span></span><br></pre></td></tr></table></figure>
<p>这样洗出来的文本”Elvira, Mistress of the Dark”就是真正有效的信息了。</p>
<p>了解文本清洗技巧之后，回到影评情感分析题本身，接下来开始正文。</p>
<h3 id="第一步：创建文本清洗函数"><a href="#第一步：创建文本清洗函数" class="headerlink" title="第一步：创建文本清洗函数"></a>第一步：创建文本清洗函数</h3><p>影评分析题的文本是英文的，首先要创建一个简单的函数，将评论清理成我们可以使用的格式。我们只想要原始文本，而不是其他相关的HTML，或其他垃圾符号。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">from</span> bs4 <span class="keyword">import</span> BeautifulSoup </span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">review_to_wordlist</span><span class="params">(review)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    Meant for converting each of the IMDB reviews into a list of words.</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    <span class="comment"># First remove the HTML.</span></span><br><span class="line">    review_text = BeautifulSoup(review).get_text()</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># Use regular expressions to only include words.</span></span><br><span class="line">    review_text = re.sub(<span class="string">"[^a-zA-Z]"</span>,<span class="string">" "</span>, review_text)</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># Convert words to lower case and split them into separate words.</span></span><br><span class="line">    words = review_text.lower().split()</span><br><span class="line">   </span><br><span class="line">    <span class="comment"># Return a list of words</span></span><br><span class="line">    <span class="comment"># return(words)</span></span><br><span class="line">    <span class="keyword">return</span>(<span class="string">" "</span>.join(words))</span><br></pre></td></tr></table></figure>
<p>加载数据，按照上面的函数将样本数据进行清洗：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"></span><br><span class="line"><span class="comment"># load data</span></span><br><span class="line">data = pd.read_csv(<span class="string">'data/labeledTrainData.tsv'</span>,delimiter=<span class="string">"\t"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># clean data</span></span><br><span class="line">clean_data = []</span><br><span class="line"><span class="keyword">for</span> rv <span class="keyword">in</span> data[<span class="string">'review'</span>]:</span><br><span class="line">    clean_data.append(review_to_wordlist(rv))</span><br><span class="line">    </span><br><span class="line">data[<span class="string">'clean_review'</span>] = clean_data</span><br></pre></td></tr></table></figure>
<p>我这里把整个labeled train data做为整个数据集，将其拆分成训练集、测试集：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn.model_selection <span class="keyword">import</span> train_test_split</span><br><span class="line"></span><br><span class="line">X_train, X_test, y_train, y_test = train_test_split(\</span><br><span class="line">            data[<span class="string">'clean_review'</span>],data[<span class="string">'sentiment'</span>], test_size=<span class="number">0.2</span>, random_state=<span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<h3 id="第二步：生成词向量"><a href="#第二步：生成词向量" class="headerlink" title="第二步：生成词向量"></a>第二步：生成词向量</h3><p>先看一下影评的平均文本长度：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">data[<span class="string">'clean_review'</span>].apply(<span class="keyword">lambda</span> x: len(x.split(<span class="string">" "</span>))).mean()</span><br><span class="line"><span class="comment"># 236.82856</span></span><br></pre></td></tr></table></figure>
<p>使用keras的Tokenizer进行分词：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> keras.preprocessing.text <span class="keyword">import</span> Tokenizer</span><br><span class="line"><span class="keyword">from</span> keras.preprocessing.sequence <span class="keyword">import</span> pad_sequences</span><br><span class="line"></span><br><span class="line">max_features = <span class="number">6000</span> <span class="comment"># 字典最大数</span></span><br><span class="line">tokenizer = Tokenizer(num_words=max_features)</span><br><span class="line">tokenizer.fit_on_texts(X_train)</span><br><span class="line">list_tokenized_train = tokenizer.texts_to_sequences(X_train)</span><br><span class="line"></span><br><span class="line">maxlen = <span class="number">130</span> <span class="comment"># 句子最大长度</span></span><br><span class="line">X_tr = pad_sequences(list_tokenized_train, maxlen=maxlen)</span><br></pre></td></tr></table></figure>
<h3 id="第三步：-创建-分类器-模型"><a href="#第三步：-创建-分类器-模型" class="headerlink" title="第三步： 创建 分类器/模型"></a>第三步： 创建 分类器/模型</h3><p>天底下的分类器千千万，可以随自己选几个尝试一下。</p>
<p><strong>BiLSTM Classifier</strong> </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> keras.layers <span class="keyword">import</span> Dense , Input , LSTM , Embedding, Dropout , Activation, GRU, Flatten</span><br><span class="line"><span class="keyword">from</span> keras.layers <span class="keyword">import</span> Bidirectional, GlobalMaxPool1D</span><br><span class="line"><span class="keyword">from</span> keras.models <span class="keyword">import</span> Model, Sequential</span><br><span class="line"><span class="keyword">from</span> keras.layers <span class="keyword">import</span> Convolution1D</span><br><span class="line"><span class="keyword">from</span> keras <span class="keyword">import</span> initializers, regularizers, constraints, optimizers, layers</span><br><span class="line"></span><br><span class="line">embed_size = <span class="number">256</span></span><br><span class="line">model = Sequential()</span><br><span class="line">model.add(Embedding(max_features, embed_size))</span><br><span class="line">model.add(Bidirectional(LSTM(<span class="number">32</span>, return_sequences = <span class="keyword">True</span>)))</span><br><span class="line">model.add(GlobalMaxPool1D())</span><br><span class="line">model.add(Dense(<span class="number">20</span>, activation=<span class="string">"relu"</span>))</span><br><span class="line">model.add(Dropout(<span class="number">0.05</span>))</span><br><span class="line">model.add(Dense(<span class="number">1</span>, activation=<span class="string">"sigmoid"</span>))</span><br><span class="line">model.compile(loss=<span class="string">'binary_crossentropy'</span>, optimizer=<span class="string">'adam'</span>, metrics=[<span class="string">'accuracy'</span>])</span><br><span class="line"></span><br><span class="line">batch_size = <span class="number">100</span></span><br><span class="line">epochs = <span class="number">5</span></span><br><span class="line">model.fit(X_tr,y_train, batch_size=batch_size, epochs=epochs, validation_split=<span class="number">0.2</span>)</span><br></pre></td></tr></table></figure>
<p>需要一点时间，运行时会出现：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Train on <span class="number">16000</span> samples, validate on <span class="number">4000</span> samples</span><br><span class="line">Epoch <span class="number">1</span>/<span class="number">5</span></span><br><span class="line"><span class="number">16000</span>/<span class="number">16000</span> [==============================] - <span class="number">31</span>s <span class="number">2</span>ms/step - loss: <span class="number">0.4832</span> - acc: <span class="number">0.7597</span> - val_loss: <span class="number">0.3214</span> - val_acc: <span class="number">0.8608</span></span><br><span class="line">Epoch <span class="number">2</span>/<span class="number">5</span></span><br><span class="line"><span class="number">16000</span>/<span class="number">16000</span> [==============================] - <span class="number">30</span>s <span class="number">2</span>ms/step - loss: <span class="number">0.2633</span> - acc: <span class="number">0.8929</span> - val_loss: <span class="number">0.3142</span> - val_acc: <span class="number">0.8642</span></span><br><span class="line">Epoch <span class="number">3</span>/<span class="number">5</span></span><br><span class="line"><span class="number">16000</span>/<span class="number">16000</span> [==============================] - <span class="number">30</span>s <span class="number">2</span>ms/step - loss: <span class="number">0.1876</span> - acc: <span class="number">0.9292</span> - val_loss: <span class="number">0.3474</span> - val_acc: <span class="number">0.8557</span></span><br><span class="line">Epoch <span class="number">4</span>/<span class="number">5</span></span><br><span class="line"><span class="number">16000</span>/<span class="number">16000</span> [==============================] - <span class="number">29</span>s <span class="number">2</span>ms/step - loss: <span class="number">0.1211</span> - acc: <span class="number">0.9593</span> - val_loss: <span class="number">0.4179</span> - val_acc: <span class="number">0.8560</span></span><br><span class="line">Epoch <span class="number">5</span>/<span class="number">5</span></span><br><span class="line"><span class="number">16000</span>/<span class="number">16000</span> [==============================] - <span class="number">29</span>s <span class="number">2</span>ms/step - loss: <span class="number">0.0760</span> - acc: <span class="number">0.9754</span> - val_loss: <span class="number">0.5393</span> - val_acc: <span class="number">0.8440</span></span><br><span class="line">&lt;keras.callbacks.History at <span class="number">0x2684c124940</span>&gt;</span><br></pre></td></tr></table></figure>
<h3 id="第四步：-模型评估"><a href="#第四步：-模型评估" class="headerlink" title="第四步： 模型评估"></a>第四步： 模型评估</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">list_sentences_test = X_test</span><br><span class="line">list_tokenized_test = tokenizer.texts_to_sequences(list_sentences_test)</span><br><span class="line">X_te = pad_sequences(list_tokenized_test, maxlen=maxlen)</span><br><span class="line">prediction = model.predict(X_te)</span><br><span class="line">y_pred = (prediction &gt; <span class="number">0.5</span>)</span><br><span class="line"><span class="keyword">from</span> sklearn.metrics <span class="keyword">import</span> f1_score, confusion_matrix</span><br><span class="line">print(<span class="string">'F1-score: &#123;0&#125;'</span>.format(f1_score(y_pred, y_test)))</span><br><span class="line">print(<span class="string">'Confusion matrix:'</span>)</span><br><span class="line">confusion_matrix(y_pred, y_test)</span><br></pre></td></tr></table></figure>
<p>评估结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">F1-score: <span class="number">0.8357478065700876</span></span><br><span class="line">Confusion matrix:</span><br><span class="line">array([[<span class="number">2147</span>,  <span class="number">449</span>],</span><br><span class="line">       [ <span class="number">356</span>, <span class="number">2048</span>]], dtype=int64)</span><br></pre></td></tr></table></figure>
<p>整个流程就差不多算完成啦，接下来就是进行模型优化，或者更换其它分类器。</p>
<h3 id="写在最后"><a href="#写在最后" class="headerlink" title="写在最后"></a>写在最后</h3><p>这篇就是简单走了个流程，仅作示例。除了本文提到的技巧，还有很多细节可以填充，比如去掉停用词等；还有细节可以优化，比如调整嵌入维度等。之后有空还会继续维护本篇，填充更多有效内容。</p>
<p>更多参考：</p>
<ul>
<li><a href="https://www.kaggle.com/sameerdev7/93-f-score-bag-of-words-m-bags-of-popcorn-with-rf" target="_blank" rel="noopener">Random Forest Classifier</a></li>
<li><a href="https://nbviewer.jupyter.org/github/jmsteinw/Notebooks/blob/master/NLP_Movies.ipynb" target="_blank" rel="noopener">Natural Language Processing in a Kaggle  Competition: Movie Reviews</a> </li>
<li><a href="https://nbviewer.jupyter.org/github/jmsteinw/" target="_blank" rel="noopener">https://nbviewer.jupyter.org/github/jmsteinw/</a></li>
<li><a href="https://www.kaggle.com/jatinmittal0001/word2vec" target="_blank" rel="noopener">https://www.kaggle.com/jatinmittal0001/word2vec</a></li>
<li><a href="https://github.com/ziyanfeng/kaggle-bag-of-words-meets-bags-of-popcorn/blob/master/notebook.ipynb" target="_blank" rel="noopener">Kaggle - Bag of Words Meets Bags of Popcorn</a> </li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>打赏2块钱，帮我买杯咖啡，继续创作，谢谢大家！☕~</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="ZhangYi WeChat Pay"/>
        <p>WeChat Pay</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/kaggle/" rel="tag"># kaggle</a>
          
            <a href="/tags/NLP/" rel="tag"># NLP</a>
          
            <a href="/tags/sentiment-analysis/" rel="tag"># sentiment analysis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/03/12/pos/" rel="next" title="POS tagging 词性标注 之 武林外传版">
                <i class="fa fa-chevron-left"></i> POS tagging 词性标注 之 武林外传版
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/10/github-commit-not-green/" rel="prev" title="解决GitHub commit不显示绿色的问题">
                解决GitHub commit不显示绿色的问题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-2691877571661707"
     data-ad-slot="1301633292"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="ZhangYi" />
            
              <p class="site-author-name" itemprop="name">ZhangYi</p>
              <p class="site-description motion-element" itemprop="description">花时间做那些别人看不见的事~！</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">42</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">80</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/YZHANG1270" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:YZHANG1270@gmail.com" target="_blank" title="邮箱">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/p/1005053340707810?is_all=1" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i></a>
                  </span>
                
            </div>
          

          
          

          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#文本清洗技巧"><span class="nav-text">文本清洗技巧</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-re：正则表达式-Regular-Expression"><span class="nav-text">1. re：正则表达式 Regular Expression</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#中文处理："><span class="nav-text">中文处理：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#英文处理："><span class="nav-text">英文处理：</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-BeautifulSoup：清洗HTML、垃圾符号"><span class="nav-text">2. BeautifulSoup：清洗HTML、垃圾符号</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第一步：创建文本清洗函数"><span class="nav-text">第一步：创建文本清洗函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第二步：生成词向量"><span class="nav-text">第二步：生成词向量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第三步：-创建-分类器-模型"><span class="nav-text">第三步： 创建 分类器/模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第四步：-模型评估"><span class="nav-text">第四步： 模型评估</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#写在最后"><span class="nav-text">写在最后</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ZhangYi</span>

  
</div>








  <div class="footer-custom">All content under <a href="https://creativecommons.org/licenses/by-nc-nd/4.0/">CC BY-NC-ND 4.0</a></div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      visitors
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>


  


  
  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://codewithzhangyi.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://codewithzhangyi.com/2019/03/12/kaggle-movie-reviews/';
          this.page.identifier = '2019/03/12/kaggle-movie-reviews/';
          this.page.title = 'Kaggle - Bag of Words Meets Bags of Popcorn';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://codewithzhangyi.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  


  

  

</body>
</html>
